package com.net.xpay.backend.scheduler;


import com.net.xpay.core.domain.ChargeRecord;
import com.net.xpay.core.enums.PayStatus;
import com.net.xpay.core.manager.ChargeRecordManager;
import com.net.xpay.core.service.ChargeService;
import com.net.shard.ShardDataSource;
import com.net.shard.ShardDataSourceConfigurer;
import com.net.shard.ShardUtil;
import com.net.shard.domain.ShardConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * 2019/7/15 16:28

 */
@Slf4j
@Component
public class ChargeScheduler {

    @Autowired
    private ChargeService chargeService;

    @Autowired
    @Qualifier("shardDataSource")
    private DataSource shardDataSource;

    @Autowired
    private ChargeRecordManager chargeRecordManager;

    /**
     * 查询充值状态
     */
    @Scheduled(cron = "*/5 * * * * *")
    public void updateChargeRecord() {
        ShardDataSourceConfigurer shardDataSourceConfigurer = ((ShardDataSource) shardDataSource).getShardDataSourceConfigurer();
        Map<Long, ShardConfig> shardConfigMap = shardDataSourceConfigurer.getShardConfigMap();
        for (Long shardId : shardConfigMap.keySet()) {
            try {
                ShardUtil.setShardContext(shardId);
                doUpdateChargeRecord();
            } catch (Exception e) {
                log.warn("updatePayTransSummary error", e);
            } finally {
                ShardUtil.cleanShardContext();
            }
        }
    }

    private void doUpdateChargeRecord() {
        List<ChargeRecord> chargeRecords = chargeRecordManager.listByStatus(PayStatus.WAIT_PAY);
        if (CollectionUtils.isEmpty(chargeRecords)) {
            return;
        }

        for (ChargeRecord chargeRecord : chargeRecords) {
            try {
                chargeService.updateCharge(chargeRecord);
            } catch (Exception e) {
                log.warn("doUpdateChargeRecord failed|id={}|userId={}", chargeRecord.getId(), chargeRecord.getUserId(), e);
            }

        }
    }
}
